package com.buluo.web.controller

import com.buluo.service.mongo.TestMongoService
import com.buluo.service.sql.TestSqlService
import com.m1905hd.common.util.Page
import com.mongodb.BasicDBObject
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam

/**
 * Created by sunhao on 2016/12/28.
 */
@Controller
@RequestMapping('test')
class TestController {

    @Autowired
    TestMongoService testMongoService

    @Autowired
    TestSqlService testSqlService

    @RequestMapping(value = 'return')
    def test(String test) {
        return [code: 2000, msg: test]
    }

    @RequestMapping(value = 'mongoList')
    def mongoList(@RequestParam(defaultValue = "0") int id,
                  @RequestParam(defaultValue = "") String title,
                  @RequestParam(defaultValue = "-1") int vip,
                  @RequestParam(defaultValue = "1") int page,
                  @RequestParam(defaultValue = "20") int size) {
        def query = [] as BasicDBObject, sort = [_created: 1] as BasicDBObject,
            reField = [title: 1, vip: 1, price: 1, director: 1, ator: 1] as BasicDBObject
        if (id != 0) {
            query.append("_id", id)
        } else {
            if (!StringUtils.isEmpty(title)) {
                query.append("title", ~/${title}/)
            }
            if (vip != -1) {
                query.append("vip", vip)
            }
            def result = this.testMongoService.list(query, sort, reField, page, size)
            return [code: 2000, data: result.data]
        }
    }

    @RequestMapping(value = 'mongoFind')
    def mongoFind(@RequestParam(defaultValue = "0") int id) {
        def result = this.testMongoService.findOne(id)
        return [code: 2000, data: result]
    }

    @RequestMapping(value = 'sqlList')
    def sqlList(@RequestParam(defaultValue = "0") int id,
                @RequestParam(defaultValue = "") String title,
                @RequestParam(defaultValue = "") String info,
                @RequestParam(defaultValue = "1") int page,
                @RequestParam(defaultValue = "20") int size) {
        def result = this.testSqlService.listTest(id, title, info, page, size) as Page
        return [code: 2000, data: result.data]
    }

    @RequestMapping(value = 'sqlFind')
    def sqlFind(@RequestParam(defaultValue = "0") int id) {
        def result = this.testSqlService.findTest(id)
        return [code: 2000, data: result]
    }

}